package com.twu.biblioteca.controller;

import com.twu.biblioteca.Menu;
import com.twu.biblioteca.library.BookLibrary;
import com.twu.biblioteca.library.Library;
import com.twu.biblioteca.Security;
import com.twu.biblioteca.User;

import java.io.IOException;
import java.io.PrintStream;

/**
 * Created with IntelliJ IDEA.
 * User: Thoughtworker
 * Date: 8/25/13
 * Time: 9:41 PM
 * To change this template use File | Settings | File Templates.
 */
public class BookController extends Controller {

    private Menu menu;

    public BookController(Security security, Library library, PrintStream printStream) {
        this.security = security;
        this.library = library;
        this.printStream = printStream;
    }

    public void showBooks() {
        ((BookLibrary)library).showBooks();
    }

    public void reserveBook(){
        User loggedUser = security.getLoggedUser();
        if(loggedUser != null){
            ((BookLibrary)library).showBooks();
            promptForBook();
        }else if(loggedUser == null && security.promptForCredentials()){
            ((BookLibrary)library).showBooks();
            promptForBook();
        }else{
            printInvalidCredentialsMessage();
        }
    }

    public void promptForBook(){
        try {
            ((BookLibrary)library).reserveBook(menu.readBookName());
        } catch (IOException e) {
            ((BookLibrary)library).reserveBook(null);
        }
    }

    public void printInvalidCredentialsMessage(){
        printStream.println("Invalid user credentials!") ;
    }

    public void setMenu(Menu menu) {
        this.menu = menu;
    }


}
